package com.example.ekupiandroid;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLEncoder;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.*;

import android.util.Log;

public class WebServiceRequest {
	private static final int CONN_TIMEOUT = 5000;
	private static final int SOCKET_TIMEOUT = 10000;
	private static final String TAG = "WebServiceTask";
	
	private ArrayList<NameValuePair> params;
	private ArrayList <NameValuePair> headers;
	
	private int taskType;
	
	public static final int POST_TASK = 1;
	public static final int GET_TASK = 2;
	public static final int PUT_TASK = 3;
	public static final int DELETE_TASK = 4;
	
	
	public WebServiceRequest(int taskType) {
		this.taskType = taskType;
		params = new ArrayList<NameValuePair>();
		headers = new ArrayList<NameValuePair>();
		}
	
	
	public String Execute (String url) {
		String result = "";
		HttpResponse response = doResponse(url);
		try {
			result = inputStreamToString(response.getEntity().getContent());
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}
	
	
	private static String inputStreamToString(InputStream is) {

        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }
	
	
	public void AddNameValuePair(String name, String value) {
			params.add(new BasicNameValuePair(name, value));
		}
	
	public void AddHeader(String name, String value)
    {
        headers.add(new BasicNameValuePair(name, value));
    }
		
	
	HttpParams getHttpParams() {
			HttpParams htpp = new BasicHttpParams();
			HttpConnectionParams.setConnectionTimeout(htpp, CONN_TIMEOUT);
			HttpConnectionParams.setSoTimeout(htpp, SOCKET_TIMEOUT);
			return htpp;
		}
	
	private HttpResponse doResponse(String url) {
		HttpClient httpclient = new DefaultHttpClient(getHttpParams());
		HttpResponse response = null;
		try {
			switch (taskType) {
			case POST_TASK:
				HttpPost httppost = new HttpPost(url);
				httppost.setEntity(new UrlEncodedFormEntity(params));
				response = httpclient.execute(httppost);
				break;
			case GET_TASK:
				
				String combinedParams = "";
                if(!params.isEmpty()){
                    combinedParams += "?";
                    for(NameValuePair p : params)
                    {
                        String paramString = p.getName() + "=" + URLEncoder.encode(p.getValue(),"UTF-8");
                        if(combinedParams.length() > 1)
                        {
                            combinedParams  +=  "&" + paramString;
                        }
                        else
                        {
                            combinedParams += paramString;
                        }
                    }
                }
				HttpGet httpget = new HttpGet(url);
				for(NameValuePair h : headers)
                {
					httpget.addHeader(h.getName(), h.getValue());
                }
				
				response = httpclient.execute(httpget);
				break;
			case PUT_TASK:
				HttpPut httpput = new HttpPut(url);
				for(NameValuePair h : headers)
                {
					httpput.addHeader(h.getName(), h.getValue());
                }
				httpput.setEntity(new UrlEncodedFormEntity(params));
				response = httpclient.execute(httpput);
				break;
			case DELETE_TASK:
				HttpDelete delete = new HttpDelete(url);
				httpclient.execute(delete);
				break;
			}
		} catch (Exception e) {
			Log.e(TAG, e.getLocalizedMessage(), e);
		}
		return response;
	}
}
